package com.reader.api.controller;

import com.reader.api.constants.DeviceInfoConstants;
import com.reader.api.entity.usercenter.DeviceInfo;
import com.reader.api.service.usercenter.IUserService;
import com.reader.core.exception.CustomException;
import com.reader.core.utils.CommonVariable;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by jiahaikukn on 2017/8/8.
 */

public abstract class BaseController<T> {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private IUserService userService;



    /**
     * 获取header中的token
     * @return
     */
    protected  String getHeaderToken(){
        String token= request.getHeader(CommonVariable.TOKEN);
        if(StringUtils.isBlank(token)){
            throw new CustomException("访问凭证不合法!");
        }
        return token;
    }

    /**
     *  登录成功后获取app user id,必须是登录成功后再调用该方法，此时header中才有token
     * @return
     */
    protected  Integer getUserId(){
       String token=getHeaderToken();
       Integer userId=userService.getUserIdByToken(token);
        if(userId==null){
            throw new CustomException("用户无效，请重新登录"); //如果redis取不到userid则需要重新登录
        }
       return userId;
    }


    /**
     * 获取用户设备信息
     * @return
     */
    protected DeviceInfo getDeviceInfo(){
        String token=request.getHeader(CommonVariable.TOKEN);
        String deviceID=request.getHeader(DeviceInfoConstants.DEVICE_ID);
        String deviceModelType=request.getHeader(DeviceInfoConstants.DEVICE_MODEL_TYPE);
        DeviceInfo deviceInfo= new DeviceInfo();
        deviceInfo.setToken(token);
        deviceInfo.setDeviceId(deviceID);
        deviceInfo.setDeviceModelType(deviceModelType);
        return deviceInfo;
    }

}
